<template>
  <div
    ref="scrollContainer"
    class="scroll-container"
    @wheel.prevent="handleScroll"
  >
    <div
      ref="scrollWrapper"
      class="scroll-wrapper"
      :style="{ transform: `translateX(${left}px)` }"
    >
      <slot />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'

// 发射事件
const emit = defineEmits<{
  scroll: [value: any]
}>()

// 响应式数据
const scrollContainer = ref<HTMLElement>()
const scrollWrapper = ref<HTMLElement>()
const left = ref(0)

// 计算可移动距离
const calculateMoveDistance = (delta: number) => {
  const container = scrollContainer.value
  const wrapper = scrollWrapper.value
  
  if (!container || !wrapper) return

  const containerWidth = container.offsetWidth
  const wrapperWidth = wrapper.offsetWidth

  if (delta > 0) {
    left.value = Math.min(0, left.value + delta)
  } else {
    if (containerWidth - left.value < wrapperWidth) {
      left.value = Math.max(containerWidth - wrapperWidth, left.value + delta)
    }
  }
}

// 处理滚动
const handleScroll = (e: WheelEvent) => {
  const delta = e.deltaY || e.detail || e.wheelDelta
  calculateMoveDistance(-delta / 4)
  emit('scroll')
}

// 移动到指定位置
const moveToTarget = (currentTag: HTMLElement) => {
  const container = scrollContainer.value
  if (!container) return

  const containerWidth = container.offsetWidth
  const tagOffsetLeft = currentTag.offsetLeft
  const tagWidth = currentTag.offsetWidth

  if (tagOffsetLeft < -left.value) {
    // 标签在可视区域左侧
    left.value = -tagOffsetLeft + 20
  } else if (tagOffsetLeft > -left.value && tagOffsetLeft + tagWidth < -left.value + containerWidth) {
    // 标签完全在可视区域内，不需要移动
  } else {
    // 标签在可视区域右侧
    left.value = -(tagOffsetLeft - (containerWidth - tagWidth) + 20)
  }
}

// 暴露方法给父组件
defineExpose({
  moveToTarget
})

// 生命周期
onMounted(() => {
  // 可以添加键盘事件监听等
})

onBeforeUnmount(() => {
  // 清理事件监听
})
</script>

<style lang="scss" scoped></style>
